package com.gm.commonlib.util.PrefsUtils;

import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;

import com.youth.banner.util.LogUtils;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.Map;
public class SharePrefsFileUtils {


	public static boolean haveKey(Context context, String prefsFileName, String key) {
		SharedPreferences settings;
		settings = context.getSharedPreferences(prefsFileName, 0);
		boolean s = settings.contains(key);
		return s;
	}

	public static void setSharePrefsFileValue(Context context, String prefsFileName, String key, String value){
		SharedPreferences settings;
		settings = context.getSharedPreferences(prefsFileName, 0);
		Editor edit = settings.edit();
		edit.putString(key, value);
		edit.commit();
	}
	
	public static String getSharePrefsFileValue(Context context, String prefsFileName, String key) {
		SharedPreferences settings;
		settings = context.getSharedPreferences(prefsFileName, 0);
		String s = settings.getString(key, "");
		return s;
	}
	
	public static void removeSharePrefsFileValue(Context context, String prefsFileName, String key) {
		SharedPreferences settings;
		settings = context.getSharedPreferences(prefsFileName, 0);
		Editor edit = settings.edit();
		edit.remove(key);
		edit.commit();
	}
	
	/**
	 * 清除某一类特定缓存,通过遍历HASHMAP下的所有对象，来判断它的KEY与传入的TYPE是否匹配
	 * @param context
	 * @param prefsFileName
	 * @param keyType
	 */
	public static void removeAll(Context context, String prefsFileName, String keyType) {
		SharedPreferences settings;
		settings = context.getSharedPreferences(prefsFileName, 0);
		Map<String, ?> allKeys = settings.getAll();
		Iterator it = allKeys.entrySet().iterator();
		String key;
		ArrayList<String> arr = new ArrayList<String>();
		try {
			while (it.hasNext()) {
				java.util.Map.Entry entry = (java.util.Map.Entry) it.next();
				key = (String) entry.getKey();
				if (key.startsWith(keyType)) { // 如果匹配则删除掉
					arr.add(key);
				}
			}
			Editor edit = settings.edit();
			for (int k = 0; k < arr.size(); k++) {
				edit.remove(arr.get(k));
			}
			edit.commit();
		} catch (Exception ex) {
			LogUtils.d("# call removeAll cache failed. e:" + ex.getLocalizedMessage());
		}
	}
	
	public static void clearAllSharePrefsFileValue(Context context, String prefsFileName) {
		SharedPreferences settings;
		settings = context.getSharedPreferences(prefsFileName, 0);
		Editor edit = settings.edit();
		edit.clear();
		edit.commit();
	}
	
}
